package com.demo.gulimall.ware.mqlistener;

import com.demo.gulimall.common.to.mq.StockLockedTo;
import com.demo.gulimall.ware.service.*;
import com.demo.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Chen Yuan
 * @create 2023-07-04  14:55
 */
@Slf4j
@Component
@RabbitListener(queues = {"stock.release.queue"})
public class StockReleaseListener {
	@Autowired
	private WareSkuService wareSkuService;

	/**
	 * 库存消息过期
	 * 自动解锁库存
	 */
	@RabbitHandler
	public void handleReleaseLockedStock(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
		Boolean hasUnlock = true;
		try {
			hasUnlock = wareSkuService.handleReleaseLockedStock(stockLockedTo);

			if (hasUnlock) {
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			}else {
				channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
			}
		} catch (Exception e) {
			channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
		}
	}

	/**
	 * 订单关闭消息过期
	 * 自动解锁库存
	 */
	@RabbitHandler
	public void handleReleaseLockedStock(OrderVo order, Message message, Channel channel) throws IOException {
		Boolean hasUnlock = true;
		try {
			log.info("--> 订单已关闭 - 解锁对应库存 - orderSn:{}", order.getOrderSn());

			hasUnlock = wareSkuService.handleReleaseLockedStock(order);

			if (hasUnlock) {
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			}else {
				channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
			}
		} catch (Exception e) {
			channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
		}
	}
}
